package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.internal.TextWatcherAdapter;

public class SettingInfoActivity extends AppCompatActivity {

    private SharedPreferences.Editor edit;
    private EditText et_name;
    private EditText et_phone;
    private SharedPreferences preferences;
    private EditText et_all;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_setting_info);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        et_name = findViewById(R.id.et_name);
        et_phone = findViewById(R.id.et_phone);
        et_all = findViewById(R.id.et_all);

        preferences = getSharedPreferences("phones", MODE_PRIVATE);
        edit = preferences.edit();


        findViewById(R.id.btn_save).setOnClickListener(v -> {
            et_all.setVisibility(EditText.INVISIBLE);

            String name = et_name.getText().toString().trim();
            String phone = et_phone.getText().toString().trim();
            if (phone.isEmpty() && !name.isEmpty()) {
//                删除
                edit.remove(name);
            } else if (!name.isEmpty()) {
                edit.putString(name, phone);
                String desc = String.format("姓名：%s\n电话：%s保存成功", name, phone);
                Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "显示所有信息", Toast.LENGTH_SHORT).show();
            }
            edit.apply();
            showAll();
        });

        findViewById(R.id.btn_config).setOnClickListener(v -> {
            Intent intent = new Intent(this, ConfigActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        finish();
    }

    private void showAll() {
        StringBuilder tmp = new StringBuilder();
        for (String key : preferences.getAll().keySet()) {
            String value = preferences.getString(key, "");
            tmp.append(String.format("%s: %s\n", key, value));
        }
        if (tmp.length() == 0) {
            tmp.append("暂时没有联系人请添加联系人");
        }
        et_all.setText(tmp.toString());
        et_all.setVisibility(EditText.VISIBLE);
    }
}